package com.gelian.demo;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;

import com.alipay.euler.andfix.patch.PatchManager;
import com.gelian.demo.utils.SpUtils;
import com.gelian.demo.utils.Toastor;
//import com.gelian.demo.utils.UploadUtil;
import com.gelian.geliansdk.GlManager;
import com.gelian.geliansdk.GlConstant;
import com.gelian.geliansdk.GlResultCode;
import com.gelian.geliansdk.callback.GlCallback;
import com.gelian.geliansdk.callback.QueryUploadProgresCallback;
import com.gelian.geliansdk.listener.GlListener;
import com.gelian.library.CustomLightWaveView;
import com.gelian.library.callback.InitializeCallback;
import com.gelian.geliansdk.GlEngine;
import com.gelian.library.model.GlDevice;
import com.gelian.library.model.GlFileInfo;
//import com.gelian.library.b.f;

import org.simple.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends Activity {
    private static final String TAG = MainActivity.class.getSimpleName();
    public static Activity mContext;
    String phoneNum = "";
    String password = "";
    //    String product_id = "30001110010001";
    //        String product_id = "31000020010001";
    String product_id = "30000000000000";
    //    String id;

    List<GlDevice> deviceList = new ArrayList<>();
    public List<String> LIST_UPLOADING = new ArrayList<>();
    public static final String SPLIT_STR = "#";
    @Bind(R.id.vercode_et)
    EditText vercodeEt;

    @Bind(R.id.register_et)
    EditText registerEt;

    @Bind(R.id.login_et)
    EditText loginEt;
    @Bind(R.id.device_list_lv)
    ListView deviceListLv;

    AdapterDeviceList adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        ButterKnife.bind(this);
        phoneNum = SpUtils.getInstance().getMobileId();
        registerEt.setText(phoneNum);

        password = SpUtils.getInstance().getUserPass();
        loginEt.setText(password);

        initSDK();


        adapter = new AdapterDeviceList(this, deviceList);
        deviceListLv.setAdapter(adapter);

    }


    @OnClick({
            R.id.get_vercode_btn,
            R.id.register_btn,
            R.id.light_btn,
            R.id.login_btn
    })
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.get_vercode_btn://获取验证码
                getVercode();
                break;
            case R.id.register_btn://注册
                register();
                break;
            case R.id.login_btn://登录
                login();
                break;
            case R.id.light_btn://
                Toastor.showToast("敬请期待");
                break;
        }
    }


    private void getVercode() {
        vercodeEt.setText("");

        //从界面上获取输入的内容
        phoneNum = registerEt.getText().toString().trim();
        if (TextUtils.isEmpty(phoneNum)) {
            vercodeEt.setHint("请输入正确的手机号码");
            return;
        }

        vercodeEt.setHint("正在获取验证码...");
        SpUtils.getInstance().saveMobileId(phoneNum);


        //调用sdk的获取验证码方法
        GlEngine.requestPhoneIdentify(phoneNum, new GlCallback() {
            @Override
            public void done(int resultCode) {
                if (resultCode == GlResultCode.GL_CALLBACK_CODE_SUCCESS) {
                    vercodeEt.setHint("获取验证码成功");
                } else {
                    vercodeEt.setHint("失败:" + resultCode);
                }
            }

        });
    }

    private void register() {
        String vercode = vercodeEt.getText().toString().trim();
        if (TextUtils.isEmpty(vercode)) {
            Toastor.showToast("验证码不能为空");
            return;
        }

        phoneNum = registerEt.getText().toString().trim();
        if (TextUtils.isEmpty(phoneNum)) {
            Toastor.showToast("请输入正确的手机号码");
            return;
        }
        SpUtils.getInstance().saveMobileId(phoneNum);
        password = loginEt.getText().toString().trim();
        if (TextUtils.isEmpty(password)) {
            Toastor.showToast("请输入正确的密码");
            return;
        }
        SpUtils.getInstance().setUserPass(password);
        vercodeEt.setText("");
        vercodeEt.setHint("注册中...");

        GlEngine.registerByPhoneNum(phoneNum, vercode, password, new GlCallback() {
            @Override
            public void done(int resultCode) {
                if (resultCode == GlResultCode.GL_CALLBACK_CODE_SUCCESS) {
                    vercodeEt.setHint("注册成功");
                    //                    login();
                } else if (resultCode == GlResultCode.GL_CALLBACK_CODE_USER_EXIST) {
                    vercodeEt.setHint("用户名已存在");
                } else {
                    vercodeEt.setHint("失败:" + resultCode);
                }
            }
        });
    }

    private void login() {
        vercodeEt.setText("");
        phoneNum = registerEt.getText().toString().trim();
        if (TextUtils.isEmpty(phoneNum)) {
            vercodeEt.setHint("请输入正确的手机号码");
            return;
        }
        SpUtils.getInstance().saveMobileId(phoneNum);
        password = loginEt.getText().toString().trim();
        if (TextUtils.isEmpty(password)) {
            vercodeEt.setHint("请输入正确的密码");
            return;
        }
        SpUtils.getInstance().setUserPass(password);

        vercodeEt.setHint("登录中");
        GlEngine.login(phoneNum, password, new GlCallback() {
            @Override
            public void done(int resultCode) {
                if (resultCode == GlResultCode.GL_CALLBACK_CODE_SUCCESS) {
                    vercodeEt.setHint("登录成功");
                } else {
                    vercodeEt.setHint("登录失败:" + resultCode);
                }
            }
        });
    }


    private void initSDK() {
        //        PushManager.getInstance().initialize(this);
        GlManager.initialize(this     //上下文对象
                , product_id          //厂商id ,从个联开放平台申请
                , false               //是否只使用远程功能(如果传入true,则没有局域网功能)
                , new GlListener() {  //个联监听接口

                    /**
                     * 账号在别的手机登录
                     */
                    @Override
                    public void otherLoginNotice() {
                        Toastor.showToast("异地登录，你已下线");
                    }

                    /**
                     * 数据透传(来自设备)
                     * @param id                设备的id
                     * @param payloadData        透传的数据
                     */
                    @Override
                    public void receivePayloadFromDevice(String id, byte[] payloadData) {
                        //                        Toastor.showToast("来自" + id + "设备的数据:" + new String(payloadData));

                        String postMsg = id + "-" + new String(payloadData);
                        EventBus.getDefault().post(postMsg, AppConstant.REC_THROUGH_DATA);
                    }

                    /**
                     * 数据透传(来自云端)
                     * @param payloadData       透传的数据
                     */
                    @Override
                    public void receivePayloadFromSever(byte[] payloadData) {
                        Toastor.showToast("来自云端的数据:" + new String(payloadData));
                    }

                    /**
                     * 文件共享(来自设备)
                     * @param imei           共享文件的设备imei
                     * @param glFileInfo   文件信息对象
                     */
                    @Override
                    public void receiveFileFromDevice(String imei, GlFileInfo glFileInfo) {
                    }

                    /**
                     *  设备列表有变化
                     * @param glDevices  设备对象的列表,设备对象包含设备id,昵称,是否在线等一系列信息
                     */
                    @Override
                    public void deviceListChange(List<GlDevice> glDevices) {
                        deviceList.clear();
                        deviceList.addAll(glDevices);
                        adapter.notifyDataSetChanged();

                        boolean flag = false;
                        for (GlDevice glDevice : glDevices) {
                            if (glDevice.getImei().equals(AdapterDeviceList.lastClickId)) {
                                flag = true;
                                EventBus.getDefault().post(glDevice, AppConstant.NOTIFY_SINGLE_DEVICE_UI);
                            }
                        }

                        if (!flag) {
                            EventBus.getDefault().post(new GlDevice(), AppConstant.NOTIFY_SINGLE_DEVICE_UI);
                        }
                    }

                    /**
                     * 收到权限请求
                     * <p/>
                     * 当其他用户申请绑定一个私有权限的设备的时候，该设备的管理员用户会收到申请通知
                     * @param id               设备的唯一id
                     * @param applyName        申请者用户名
                     * @param responseMessage  该次申请的唯一标识，响应时候将其传入sdk
                     */
                    @Override
                    public void receivedPermissionRequest(String id, String applyName, String responseMessage) {
                        Toastor.showLongToast(applyName + "申请绑定您的:" + id + "设备");
                    }

                    /**
                     * 收到权限请求的处理结果
                     * <p/>
                     * 当设备管理员批复用户的权限申请，该用户会收到处理结果通知
                     * @param id               设备的唯一id
                     * @param isApprove        是否同意
                     */
                    @Override
                    public void receivedPermissionResponse(String id, boolean isApprove) {
                        Toastor.showLongToast("管理员" + (isApprove ? "同意" : "拒绝") + "了您" + id + "设备的申请");
                    }
                }
                , new InitializeCallback() {


                    @Override
                    public void onSuccess() {
                        Toastor.showToast("初始化成功");
                    }

                    @Override
                    public void onFail() {
                        Toastor.showToast("初始化失败");
                    }
                });
    }


}
